/**
 * 
 * 本类作用：获取零部件属性
 * 
 * @author 魏文杰 
 * @Version 1.0
 * @Date 2013-10-08
 */

package ext.generic.erp.attributes;

import java.rmi.RemoteException;
import java.sql.Timestamp;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;

import com.ptc.netmarkets.model.NmOid;
import com.ptc.netmarkets.workflow.NmWorkflowHelper;

import ext.com.core.CoreUtil;
import ext.com.iba.IBAUtil;
import ext.generic.erp.common.CommonPDMUtil;
import ext.generic.erp.config.ERPPartTemplateUtil;
import ext.generic.part.CusIBAUtil;
import ext.generic.workflow.WorkflowUtil;
import ext.tianma.part.CheckPartReveal;
import ext.tianma.part.forms.TMTypeUtil;
import wt.enterprise.MadeFromLink;
import wt.fc.Persistable;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.fc.WTObject;
import wt.method.RemoteAccess;
import wt.org.DirectoryContextProvider;
import wt.org.GenericDirectoryContextProvider;
import wt.org.OrganizationServicesHelper;
import wt.org.WTPrincipal;
import wt.org.WTPrincipalReference;
import wt.org.WTUser;
import wt.part.WTPart;
import wt.project.Role;
import wt.team.Team;
import wt.team.TeamManaged;
import wt.team.TeamReference;
import wt.util.WTException;
import wt.workflow.engine.StandardWfEngineService;
import wt.workflow.engine.WfEngineHelper;
import wt.workflow.engine.WfProcess;
import wt.workflow.engine.WfState;
import wt.workflow.work.WfAssignedActivity;
import wt.workflow.work.WorkItem;

public class PartAttribute implements RemoteAccess {

	private static final String CREATOR = "creator";

	private static final String TRACE_CODE = "traceCode";

	private static final String DEFAULT_UNIT = "defaultUnit";

	private static final String LIFECYCLE = "lifecycle";

	private static final String MODIFIER = "modifier";

	private static final String MODIFY_TIME = "modifyTime";

	private static final String NAME = "name";

	private static final String NUMBER = "number";

	private static final String SOURCE = "source";

	private static final String VIEW = "view";

	// 零部件完整版本，包括大版本和小版本，通常形如：A.1
	private static final String VERSION = "version";

	// 零部件大版本
	private static final String MAJOR_VERSION = "majorVersion";

	// 零部件小版本
	private static final String MINOR_VERSION = "minorVersion";

	// 零部件软类型
	private static final String PART_SOFT_TYPE = "part_type";

	private static final String PART_CATEGORY = "partCategory";

	private static final String PART_TEMPLATE = "partTemplate";

	private static final String RESOLUTION = "resolution";

	private static final String PART_NUMBER_EFFECTIVE_SITE = "partNumberEffectiveSite";

	// 供应商
	private static final String PART_SUPPLIER = "partSupplier";

	// 成品的模组产地
	private static final String MODULEORIGIN = "moduleOrigin";

	// 部分原材料传到sourcing，需要传PM信息
	private static final String PMEMAIL = "PMEmail";
	
	// 部分原材料传到sourcing，需要传PM信息
	private static final String SECONDSUPPLIERPARTNUMBER = "secondSupplierPartNumber";
	
	// 部分原材料传到sourcing，二供物料流程
	private static final String PROCESSNAME = "二供物料编码申请流程";
	
	private static final String ACTIVITYNAME = "PM审核(推动RD及时发包)";

	/**
	 * 获取零部件属性信息
	 * 
	 * @param part
	 * @param attributeName
	 * @return
	 */
	protected static String getAttribute(WTPart part, String attributeName) {
		String attributeValue = "";

		try {
			if (attributeName.equals(CREATOR)) {

				attributeValue = CommonPDMUtil.getCreatorName(part);

			} else if (attributeName.equals(TRACE_CODE)) {

				attributeValue = CommonPDMUtil.getTraceCode(part);

			} else if (attributeName.equals(DEFAULT_UNIT)) {

				attributeValue = CommonPDMUtil.getERPMappingUnit(part);

			} else if (attributeName.equals(LIFECYCLE)) {

				attributeValue = CommonPDMUtil.getLifecycle(part);

			} else if (attributeName.equals(MODIFIER)) {

				attributeValue = CommonPDMUtil.getModifierName(part);

			} else if (attributeName.equals(MODIFY_TIME)) {

				attributeValue = CommonPDMUtil.getModifyTime(part);

			} else if (attributeName.equals(NAME)) {

				attributeValue = part.getName();

			} else if (attributeName.equals(NUMBER)) {

				attributeValue = part.getNumber();

			} else if (attributeName.equals(SOURCE)) {

				attributeValue = CommonPDMUtil.getSourceCN(part);

			} else if (attributeName.equals(VIEW)) {

				attributeValue = part.getViewName();

			} else if (attributeName.equals(MAJOR_VERSION)) {

				attributeValue = CommonPDMUtil.getMajorVersion(part);

			} else if (attributeName.equals(MINOR_VERSION)) {

				attributeValue = CommonPDMUtil.getMinorVersion(part);

			} else if (attributeName.equals(VERSION)) {

				attributeValue = CommonPDMUtil.getVersion(part);

			} else if (attributeName.equals(PART_SOFT_TYPE)) {

				attributeValue = CommonPDMUtil.getSoftType(part);

			} else if (attributeName.equals(RESOLUTION)) {
				String resolutionH = (String) IBAUtil.getIBAValue(part,
						"finishedGoodResolutionH");
				String resolutionV = (String) IBAUtil.getIBAValue(part,
						"finishedGoodResolutionV");

				if (resolutionH == null) {
					resolutionH = "";
				} else {
					resolutionH = resolutionH.trim();
				}

				if (resolutionV == null) {
					resolutionV = "";
				} else {
					resolutionV = resolutionV.trim();
				}

				if ((!resolutionH.equals("")) && (!resolutionV.equals(""))) {
					attributeValue = resolutionH + "X" + resolutionV;
				} else {
					attributeValue = resolutionH + resolutionV;
				}

			} else if (attributeName.equals(PART_CATEGORY)) {

				attributeValue = ERPPartTemplateUtil.getERPPartCategory(part);

			} else if (attributeName.equals(PART_TEMPLATE)) {

				attributeValue = ERPPartTemplateUtil.getERPPartTemplate(part);

			} else if (attributeName.equals("partInspectionStandard")) {

				String ibaValue = (String) IBAUtil.getIBAValue(part,
						attributeName);

				if (ibaValue != null && !ibaValue.isEmpty()) {
					attributeValue = EnumerationUtil
							.getEnumerationDisplayValue("检验标准", ibaValue);
				}

			} else if (attributeName.equals("finishedGoodDisplayMode")) {

				String ibaValue = (String) IBAUtil.getIBAValue(part,
						attributeName);

				if (ibaValue != null && !ibaValue.isEmpty()) {
					attributeValue = EnumerationUtil
							.getEnumerationDisplayValue("显示模式", ibaValue);
				}

			} else if (attributeName.equals(PART_NUMBER_EFFECTIVE_SITE)) {

				String ibaValue = (String) IBAUtil.getIBAValue(part,
						attributeName);

				if (ibaValue == null || ibaValue.trim().isEmpty()) {
					String view = part.getViewName();
					if (view != null && !view.trim().isEmpty()
							&& !view.trim().equals("Design")) {
						attributeValue = view.trim();
					}
				} else {
					attributeValue = ibaValue.trim();
				}
				// 新增供应商，author xuge_ning
			} else if (attributeName.equals(PART_SUPPLIER)
					&& (TMTypeUtil.isPolarizer(part)
							|| TMTypeUtil.isTopPolarizer(part)
							|| TMTypeUtil.isBotPolarizer(part) || TMTypeUtil
								.isPhantomPolarizer(part))) {

				String ibaValue = (String) IBAUtil.getIBAValue(part,
						attributeName);

				if (ibaValue != null && !ibaValue.isEmpty()) {
					attributeValue = EnumerationUtil
							.getEnumerationDisplayValue("供应商名称", ibaValue);
				}

			} else if (attributeName.equals(MODULEORIGIN)) {

				Vector modelOrigin = (Vector) IBAUtil.getIBAValue2(part,
						attributeName);
				if (modelOrigin != null) {
					for (int i = 0; i < modelOrigin.size(); i++) {
						Object obj = modelOrigin.get(i);
						if (obj != null && obj instanceof String) {
							if (attributeValue.equals("")) {
								attributeValue = (String) obj;
							} else {
								attributeValue = attributeValue + "|"
										+ (String) obj;
							}
						}
					}
				}
				//新增PM的email信息
			} else if (attributeName.equals(PMEMAIL)) {
				if("Y".equals(CheckPartReveal.setPMAudit(part))){
					attributeValue = getPMEmailbyprocess(part).trim();
					if(attributeValue != null && !"".equals(attributeValue)){
						WTUser user = getUserByName(attributeValue);
						System.out.println("===========>>"+user.getFullName());
						if(user!=null) {
						 attributeValue = user.getEMail();
						}
					}
				}
			} else if (attributeName.equals(SECONDSUPPLIERPARTNUMBER)) {
				if(TMTypeUtil.isRawMaterial(part) && isRelatedRunningProcess(part)){
					WTPart designPart = CommonPDMUtil.getWTPartByNumViewAndVersion(part.getNumber(), "Design", "0.0");
					QueryResult qr = PersistenceHelper.manager.navigate(designPart,"original", MadeFromLink.class, false);
					if ((qr != null) && (qr.size() > 0)) {
						WTPart orgPart = null;
						while (qr.hasMoreElements()) {
							MadeFromLink link = (MadeFromLink) qr.nextElement();
							orgPart = (WTPart) link.getOriginal();
						}
						attributeValue = orgPart.getNumber();
					}
					//System.out.println("orgPart.getNumber()" + attributeValue);
				}
			} else {
				Object valueObj = IBAUtil.getIBAValue(part, attributeName);
				if (valueObj != null) {
					attributeValue = (String) valueObj;
				} else {
					attributeValue = "";
				}

			}
		} catch (WTException wte) {
			wte.printStackTrace();
		} catch (RemoteException e) {
			e.printStackTrace();
		} finally {
			if (attributeValue == null) {
				attributeValue = "";
			}
		}

		return attributeValue;
	}
	
	/***
	 * 根据用户名称获取user
	 * 
	 * @param name
	 * @return
	 */
	private static WTUser getUserByName(String name) {
		WTUser user = null;
		try {
			String[] defaultService = OrganizationServicesHelper.manager.getDirectoryServiceNames();
			DirectoryContextProvider dcp = OrganizationServicesHelper.manager
					.newDirectoryContextProvider(defaultService, new String[] { "subtree" });
			Enumeration eee = OrganizationServicesHelper.manager.findLikeUsers("name", name,
					new GenericDirectoryContextProvider(defaultService));
			if (eee.hasMoreElements())
				user = (WTUser) eee.nextElement();
		} catch (WTException wte) {
			wte.printStackTrace();
		}
		return user;
	}

	
	/**
	 * 获取part流程中签审者PM这个节点完成者的用户信息（用户名）
	 * @param part
	 * @return
	 */
	public static String getPMEmailbyprocess(WTPart part) {
		
		String userName = "";
		try {
			WfProcess process = null;
            NmOid nmoid = NmOid.newNmOid(PersistenceHelper.getObjectIdentifier(part));
            QueryResult processes = NmWorkflowHelper.service.getRoutingHistoryData(nmoid);
			//System.out.println("part :" + part.getNumber() + " Info processes " + processes + ",boolean:"+ processes.hasMoreElements() + ",size : " + processes.size());
			while (processes.hasMoreElements()) {
				process = (WfProcess) processes.nextElement();
				System.out.println("Info process " + process);
				String name = process.getName();
				Timestamp time = process.getCreateTimestamp();
				System.out.println("Info process," + name + " 的创建时间:" + time + ",process state : " + process.getState());
				QueryResult qr = process.getContainerNodes();
				while (qr.hasMoreElements()) {
					Object obj = qr.nextElement();
					if (obj instanceof WfAssignedActivity) {
						WfAssignedActivity wfaa = (WfAssignedActivity) obj;
						//System.out.println("Info WfAssignedActivity name :"+ wfaa.getName());
						String atyName = wfaa.getName();
						if (atyName.equals(ACTIVITYNAME)) {

							QueryResult allWorkItems;
							allWorkItems = WorkflowUtil.getWorkItemByParent(wfaa);
							while (allWorkItems.hasMoreElements()) {
								WorkItem workItem = (WorkItem) allWorkItems.nextElement();
								userName = workItem.getCompletedBy();
							}
							break;
						}
					}
				}
			}
		} catch (WTException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return userName;
	}
	
	/**
	 *函数功能：判断当前的对象是不是关联正在运行的工作流
	 *输入参数：WTObject：obj 
	 *true:存在关联
	 * @throws WTException 
	 */
	public static boolean isRelatedRunningProcess(WTObject obj) throws WTException
	{
		//得到与obj关联的工作流
		WfProcess process = null;
		NmOid nmoid = NmOid.newNmOid(PersistenceHelper.getObjectIdentifier(obj));
        QueryResult processes = NmWorkflowHelper.service.getRoutingHistoryData(nmoid);
		while (processes.hasMoreElements()) {
			process = (WfProcess) processes.nextElement();
			if(process.getName().contains(PROCESSNAME)){
				return true;
			}
		}
		return false;
	}
}
